﻿using Newtonsoft.Json;
using SIG.Infrastructure.Captcha;
using SIG.Model;
using SIG.Model.Identity;
using SIG.Model.ViewModel.Identity;
using SIG.Service;
using SIG.Service.Identity;
using System;

using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace SIG.Web.Controllers
{
    public class AccountController : Controller
    {
        IUserService _userService;
        public AccountController(IUserService UserService)
        {
            _userService = UserService;
        }
        public CaptchaImageResult ShowCaptchaImage()
        {
            return new CaptchaImageResult();
        }

        // GET: Account
        public ActionResult Index()
        {
            return View();
        }

        //
        // GET: /Account/Login
        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Login(LoginVM model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if(Session["SigCaptcha"]!=null && Session["SigCaptcha"].ToString() != model.CaptchaText)
                {
                    ModelState.AddModelError("CaptchaText", "验证码不正确!");
                    return View(model);
                }

                var user = await _userService.SignIn(model);
                //var user = db.Users.Where(u => u.Username == model.UserName && u.PasswordHash == model.Password).FirstOrDefault();
                if (user != null)
                {
                    var roles = user.Roles.Select(m => m.RoleName).ToArray();

                    CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();
                    serializeModel.UserId = user.Id;
                    serializeModel.RealName = user.RealName;
                    serializeModel.Roles = roles;
                  //  serializeModel.Permissions = user.Permissions;
                 
                 
                    TimeSpan timeout = FormsAuthentication.Timeout;
                    DateTime expire = DateTime.Now.Add(timeout);
                    bool isPersist = model.RememberMe;

                    string userData = JsonConvert.SerializeObject(serializeModel);
                    

                    FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                             1,
                            user.UserName,
                             DateTime.Now,
                             expire,
                             isPersist,
                             userData);

                    string encTicket = FormsAuthentication.Encrypt(authTicket);
                    HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                    Response.Cookies.Add(faCookie);

                    //user.LastActivityDate = DateTime.Now;
                    //_userService.Update(user);

                    if (roles.Contains("系统管理员") || roles.Contains("管理员"))
                    {
                        return RedirectToAction("Index", "Home", new { area = "Admin" });
                    }
                    else if (roles.Contains("User"))
                    {
                        return RedirectToAction("Index", "User");
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }

                ModelState.AddModelError("", "无效的用户名或密码！");
            }

            return View(model);
        }

        public ActionResult AccessDenied()
        {
            return View();
        }

        [AllowAnonymous]
        public ActionResult LogOut()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Login", "Account", new { area=""});
        }
    }
}